package com.pingpang.websocketchat.send.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.ChartUser;
import com.pingpang.websocketchat.Message;
import com.pingpang.websocketchat.send.ChatSend;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 单聊
 * @author dell
 */
public class ChatSendSingle extends ChatSend{

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws JsonProcessingException {
		if (null != ChannelManager.getChannel(message.getAccept().getUserCode())) {
			
			//发送数据这里改为redis
			message.setFrom(userService.getUser(message.getFrom()));
			message.setAccept(userService.getUser(message.getAccept()));
			
			ChannelManager.getChannel(message.getAccept().getUserCode())
					.writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
			
			message.setStatus("1");
			userMsgService.addMsg(message);
		} else {
			message.setStatus("0");
			//message.setFrom(ChannelManager.getChartUser(message.getFrom().getUserCode()));
			message.setFrom(userService.getUser(message.getFrom()));
			message.setAccept(this.userService.getUser(message.getAccept()));
			userMsgService.addMsg(message);
			
			//提示给登录用户
			ChartUser from = message.getFrom();
			message.setFrom(message.getAccept());
			message.setAccept(from);
			message.setMsg("[" + message.getFrom().getUserName()+"("+message.getFrom().getUserCode()+")" + "]未上线");
			ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(message)));
		}
		
	}
}
